package com.ld.hpfs.web.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.ld.hpfs.common.jackson.JackJson;
import com.ld.hpfs.common.utils.Const;
import com.ld.hpfs.common.utils.Tools;
import com.ld.hpfs.common.utils.UnicodeReader;
import com.ld.hpfs.pojo.ExtPager;
import com.ld.hpfs.pojo.Invoice;
import com.ld.hpfs.pojo.User;
import com.ld.hpfs.pojo.customerBill;
import com.ld.hpfs.service.ReportService;
import com.ld.hpfs.web.interseptor.WebConstants;

@Controller
public class ReportController {
	private static final Logger logger = LoggerFactory
			.getLogger(ReportController.class);
	@Autowired
	private ReportService reportService;

	/*
	 * 获得报表任务grid信息
	 */
	@RequestMapping(value = "/getReportTaskGridList")
	public void getReportTaskGridList(ExtPager page, HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		ArrayList<HashMap<String, Object>> logs = new ArrayList<HashMap<String, Object>>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<Map<String, String>> field = page.getSortField();
			StringBuffer sort = new StringBuffer("");
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			String language = (String) session
					.getAttribute(WebConstants.CURRENT_LANG);
			if (user != null) {
				param.put("pageEnd", page.getStart() + page.getLimit());
				if (field != null && field.size() > 0) {
					for (Map<String, String> map : field) {
						sort.append(map.get("property") + " "
								+ map.get("direction") + ",");
					}
					param.put("orderBy", sort.substring(0, sort.length() - 1));
				} else {
					param.put("orderBy", "TASK_HID DESC");
				}
				param.put("pageStart", page.getStart() + 1);
				param.put(
						"companyId",
						Integer.parseInt(session.getAttribute(
								WebConstants.CURRENT_COMPANY).toString()));
				param.put("language", language);
				logs = reportService.getReportTaskGridList(param);
				if (logs != null && logs.size() > 0) {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", logs);
				} else {
					result.put("success", true);
					result.put("total", param.get("pageCount"));
					result.put("data", "");
				}
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			} else {
				writer.print("");
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 取得客户代码及名称
	 */
	@RequestMapping(value = "/getCustId")
	public void getCustId(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		ArrayList<HashMap<String, Object>> result = null;
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			param.put(
					"companyId",
					Integer.parseInt(session.getAttribute(
							WebConstants.CURRENT_COMPANY).toString()));
			result = reportService.getCustId(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 取得单据号
	 */
	@RequestMapping(value = "/getDocumnetNo")
	public void getDocumnetNo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		ArrayList<HashMap<String, Object>> result = null;
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			param.put(
					"companyId",
					Integer.parseInt(session.getAttribute(
							WebConstants.CURRENT_COMPANY).toString()));
			result = reportService.getDocumnetNo(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/**
	 * 取得发票号码
	 */
	@RequestMapping(value = "/getInvoiceNo")
	public void getInvoiceNo(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		ArrayList<HashMap<String, Object>> result = null;
		HashMap<String, Object> param = new HashMap<String, Object>();
		try {
			param.put(
					"companyId",
					Integer.parseInt(session.getAttribute(
							WebConstants.CURRENT_COMPANY).toString()));
			result = reportService.getInvoiceNo(param);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 写入新任务并生成报表
	 */
	@RequestMapping(value = "/generateReport", method = RequestMethod.POST)
	public void trandlate(HttpSession session, HttpServletRequest request,
			HttpServletResponse response, PrintWriter writer) {
		String report_name = (String) request.getParameter("report_name") == "" ? null
				: (String) request.getParameter("report_name");
		String report_param = (String) request.getParameter("report_param") == "" ? null
				: (String) request.getParameter("report_param");
		String detail = (String) request.getParameter("detail") == "" ? null
				: (String) request.getParameter("detail");
		HashMap<String, Object> param = new HashMap<String, Object>();
		HashMap<String, Object> result = new HashMap<String, Object>();
		// ArrayList<HashMap<String,Object>> logs = new
		// ArrayList<HashMap<String,Object>>();
		response.setContentType("text/plain;charset=UTF-8");
		try {
			User user = (User) session.getAttribute(WebConstants.CURRENT_USER);
			int companyId = Integer.parseInt(session.getAttribute(
					WebConstants.CURRENT_COMPANY).toString());
			param.put("report_name", report_name);
			param.put("report_param",
					report_param + ";user_id=" + user.getUserId());
			param.put("creator_id", user.getUserId());
			param.put("companyId", companyId);
			param.put("detail", detail);

			String lang = session.getAttribute(WebConstants.CURRENT_LANG)
					.toString();
			int check = reportService.insertReportTaskGridList(param); // 插入任务
			if (check == 0) {
				int id = reportService.getReportTaskId(); // 获取任务ID
				
				String[] billparam = report_param.split(";");
				if (billparam[0].substring(billparam[0].indexOf("=") + 1, billparam[0].length()).equals("customers_bill")) {
					try {
						customerBill(billparam, String.valueOf(companyId), lang);
					} catch (Exception e) {
						logger.error("Exception: ", e.getMessage());
					}
				}

				if (id != -1) {
					StringBuilder impUrl = new StringBuilder();
					impUrl.append(Const.PROPERTIES.getProperty("import.server.url")).append(Const.PROPERTIES.getProperty("import.server.report_method")).append(id).append("&lang=").append(lang);
					logger.debug("Import URL = {}", impUrl);
					HttpClient httpclient = new DefaultHttpClient();
					HttpGet httpget = new HttpGet(impUrl.toString());
					HttpResponse response1 = httpclient.execute(httpget);
					HttpEntity entity = response1.getEntity();
					if (entity != null) {
						InputStream instream = entity.getContent();
						try {
							String res = EntityUtils.toString(entity);
							logger.debug(res);
							Map<String, Object> retMap = JackJson.fromJsonToObject(res, Map.class);
							String resultCode = retMap.get("ResultCode").toString();
							if (resultCode.equals("0")) {
								result.put("resultcode", 0);
							} else {
								String resultMsg = retMap.get("ResultMsg").toString();
								result.put("resultcode", resultMsg);
							}
						} finally {
							instream.close();
						}
					}
				} else {
					result.put("resultcode", 9);
				}
			} else {
				result.put("resultcode", 9);
			}
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}

	/*
	 * 获得自定义报表json文件名称列表 2013.2.21
	 */
	@RequestMapping(value = "/getUserDefinedList")
	public void getUserDefinedList(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		response.setContentType("text/plain;charset=UTF-8");
		try {
			ArrayList<HashMap<String, Object>> logs = new ArrayList<HashMap<String, Object>>();
			HashMap<String, Object> result = new HashMap<String, Object>();
			File file = new File(
					Const.PROPERTIES.getProperty("report.user.define.dir"));
			File[] subFile = file.listFiles();// 获得文件夹中的文件数组
			if (subFile != null) {
				for (int i = 0; i < subFile.length; i++) {
					HashMap<String, Object> temp = new HashMap<String, Object>();
					String filename = subFile[i].getName();
					String type = StringUtils.substringAfterLast(filename, ".");
					if (!type.equalsIgnoreCase("json")) {
						continue;
					}
					String name = filename.substring(0, filename.length()
							- type.length() - 1);// 获得文件名
					temp.put("text", name);
					temp.put("iconCls", "tj-tree-file");
					temp.put("expanded", false);
					temp.put("leaf", true);
					logs.add(temp);
				}
			}
			result.put("success", true);
			result.put("children", logs);
			String returnMsg = JackJson.fromObjectToJson(result);
			logger.debug("{}", returnMsg);
			writer.print(returnMsg);
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}

	}

	/*
	 * 读取对应自定义报表json文件 2013.2.22
	 */
	@RequestMapping(value = "/getUserDefinedContent")
	public void getUserDefinedContent(HttpSession session,
			HttpServletRequest request, HttpServletResponse response,
			PrintWriter writer) {
		HashMap<String, Object> param = new HashMap<String, Object>();
		response.setContentType("text/plain;charset=UTF-8");
		String file_name = (String) request.getParameter("file_name") == "" ? null
				: (String) request.getParameter("file_name");
		HashMap<String, Object> result = new HashMap<String, Object>();
		try {
			if (file_name != null) {
				StringBuilder impUrl = new StringBuilder();
				impUrl.append(
						Const.PROPERTIES.getProperty("report.user.define.dir")
								.trim()).append("\\").append(file_name)
						.append(".json");
				File jsonfile = new File(impUrl.toString());
				// InputStreamReader read = new InputStreamReader (new
				// FileInputStream(jsonfile),"UTF-8");//数据流读取
				FileInputStream in = new FileInputStream(jsonfile);
				System.out.println("\n\n\nCODE:"
						+ Charset.defaultCharset().name() + "\n\n\n");
				BufferedReader reader = new BufferedReader(new UnicodeReader(
						in, Charset.defaultCharset().name())); // 测试去除BOM
				StringBuffer sb = new StringBuffer();
				String line;
				try {
					while ((line = reader.readLine()) != null) {// 行读取文件
						sb.append(line);
					}
				} catch (Exception e) {
					logger.error("Exception: ", e);
				}
				JSONObject dataJson = JSONObject.fromObject(sb.toString());// 转换为json格式
				logger.debug("{}", dataJson);
				writer.print(dataJson);
			} else {
				result.put("success", false);
				String returnMsg = JackJson.fromObjectToJson(result);
				logger.debug("{}", returnMsg);
				writer.print(returnMsg);
			}
		} catch (Exception e) {
			logger.error("Exception: ", e);
		} finally {
			writer.flush();
			writer.close();
		}
	}
	
	
	public void customerBill(String[] billparam, String companyId, String lang) {
		HashMap<String, Object> paramforbill = new HashMap<String, Object>();
		paramforbill.put("cpn_id", billparam[1].substring(billparam[1].indexOf("=") + 1, billparam[1].length()));
		paramforbill.put("cust_code", billparam[2].substring(billparam[2].indexOf("=") + 1, billparam[2].length()));
		paramforbill.put("doc_sno", billparam[3].substring(billparam[3].indexOf("=") + 1, billparam[3].length()));
		paramforbill.put("doc_eno", billparam[4].substring(billparam[4].indexOf("=") + 1, billparam[4].length()));
		paramforbill.put("docno_sdate", billparam[5].substring(billparam[5].indexOf("=") + 1, billparam[5].length()));
		paramforbill.put("docno_edate", billparam[6].substring(billparam[6].indexOf("=") + 1, billparam[6].length()));
		paramforbill.put("invoice_sno", billparam[7].substring(billparam[7].indexOf("=") + 1, billparam[7].length()));
		paramforbill.put("invoice_eno", billparam[8].substring(billparam[8].indexOf("=") + 1, billparam[8].length()));
		paramforbill.put("invono_sdate", billparam[9].substring(billparam[9].indexOf("=") + 1, billparam[9].length()));
		paramforbill.put("invono_edate", billparam[10].substring(billparam[10].indexOf("=") + 1, billparam[10].length()));

		ArrayList<customerBill> bill = reportService.getnums(paramforbill);
		HashMap<String, Object> pamget = new HashMap<String, Object>();
		for (int i = 0; i < bill.size(); i++) {
			pamget.put("param", "select DOCUMENT_NO, REPRODUCE_TYPE from TAX_R_DOC_REPRODUCE where COMPANY_ID = " + companyId + " and ORIGI_DOC_NO = '" + bill.get(i).getDocument_no() + "'");
			ArrayList<HashMap<String, Object>> operater1 = reportService.getCalculater(pamget);
			for (int j = 0; j < operater1.size(); j++) {
				if (!Tools.isEmpty(operater1.get(j).get("REPRODUCE_TYPE"))) {
					// 当一级操作为拆分时
					if (operater1.get(j).get("REPRODUCE_TYPE").toString().equals("S")) {
						pamget.remove("param");
						pamget.put("param", "select DOCUMENT_NO, REPRODUCE_TYPE from TAX_R_DOC_REPRODUCE where COMPANY_ID = " + companyId + " and ORIGI_DOC_NO = '" + operater1.get(j).get("DOCUMENT_NO").toString() + "'");
						ArrayList<HashMap<String, Object>> operater1s = reportService.getCalculater(pamget);
						for (int k = 0; k < operater1s.size(); k++) {
							if (!Tools.isEmpty(operater1s.get(k).get("REPRODUCE_TYPE"))) {
								// 当二级操作为拆分时
								if (operater1s.get(k).get("REPRODUCE_TYPE").toString().equals("S")) {
									pamget.remove("param");
									pamget.put("param", "select DOC_STATUS, isnull(INVOICE_CODE, '') as INVOICE_CODE, isnull(INVOICE_NO, '') as INVOICE_NO, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1s.get(k).get("DOCUMENT_NO").toString() + "'");
									ArrayList<HashMap<String, Object>> operater1s2s = reportService.getCalculater(pamget);
									String doc_status = operater1s2s.get(0).get("DOC_STATUS").toString();
									if (doc_status.equals("1") || doc_status.equals("9") || doc_status.equals("10") || doc_status.equals("11")) {
										bill.get(i).setAmount_opend(bill.get(i).getAmount_opend() + Double.valueOf(operater1s2s.get(0).get("AMOUNT_CUR_TOTAL").toString()));
										bill.get(i).setAmount_unopend(bill.get(i).getAmount_cur_total() - bill.get(i).getAmount_opend());
										bill.get(i).setRate_opend(bill.get(i).getRate_opend() + Double.valueOf(operater1s2s.get(0).get("TAX_AMOUNT").toString()));
										bill.get(i).setInvoice_code(operater1s2s.get(0).get("INVOICE_CODE").toString());
										bill.get(i).setInvoice_no(bill.get(i).getInvoice_no() + "~" + operater1s2s.get(0).get("INVOICE_NO").toString());
										bill.get(i).setInvoice_date(operater1s2s.get(0).get("INVOICE_DATE").toString());
									}
								}
								// 当二级操作为合并时
								else if (operater1s.get(k).get("REPRODUCE_TYPE").toString().equals("M")){
									pamget.remove("param");
									pamget.put("param", "select DOC_STATUS, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1s.get(k).get("DOCUMENT_NO").toString() + "'");
									ArrayList<HashMap<String, Object>> operater1s2s = reportService.getCalculater(pamget);
									String doc_status = operater1s2s.get(0).get("DOC_STATUS").toString();
									if (doc_status.equals("1") || doc_status.equals("9") || doc_status.equals("10") || doc_status.equals("11")) {
										pamget.remove("param");
										pamget.put("param", "select isnull(INVOICE_CODE, '') as INVOICE_CODE, isnull(INVOICE_NO, '') as INVOICE_NO, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1.get(j).get("DOCUMENT_NO").toString() + "'");
										ArrayList<HashMap<String, Object>> operater1s2m = reportService.getCalculater(pamget);
										bill.get(i).setAmount_opend(bill.get(i).getAmount_opend() + Double.valueOf(operater1s2m.get(0).get("AMOUNT_CUR_TOTAL").toString()));
										bill.get(i).setAmount_unopend(bill.get(i).getAmount_cur_total() - bill.get(i).getAmount_opend());
										bill.get(i).setRate_opend(bill.get(i).getRate_opend() + Double.valueOf(operater1s2m.get(0).get("TAX_AMOUNT").toString()));
										bill.get(i).setInvoice_code(operater1s2m.get(0).get("INVOICE_CODE").toString());
										bill.get(i).setInvoice_no(bill.get(i).getInvoice_no() + "~" + operater1s2m.get(0).get("INVOICE_NO").toString());
										bill.get(i).setInvoice_date(operater1s2m.get(0).get("INVOICE_DATE").toString());
									}
								}
							} 
							// 一级为拆分且无二级操作
							else {
								pamget.remove("param");
								pamget.put("param", "select DOC_STATUS, isnull(INVOICE_CODE, '') as INVOICE_CODE, isnull(INVOICE_NO, '') as INVOICE_NO, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1s.get(k).get("DOCUMENT_NO").toString() + "'");
								ArrayList<HashMap<String, Object>> operater1s0 = reportService.getCalculater(pamget);
								String doc_status = operater1s0.get(0).get("DOC_STATUS").toString();
								if (doc_status.equals("1") || doc_status.equals("9") || doc_status.equals("10") || doc_status.equals("11")) {
									bill.get(i).setAmount_opend(bill.get(i).getAmount_opend() + Double.valueOf(operater1s0.get(0).get("AMOUNT_CUR_TOTAL").toString()));
									bill.get(i).setAmount_unopend(bill.get(i).getAmount_cur_total() - bill.get(i).getAmount_opend());
									bill.get(i).setRate_opend(bill.get(i).getRate_opend() + Double.valueOf(operater1s0.get(0).get("TAX_AMOUNT").toString()));
									bill.get(i).setInvoice_code(operater1s0.get(0).get("INVOICE_CODE").toString());
									bill.get(i).setInvoice_no(bill.get(i).getInvoice_no() + "~" + operater1s0.get(0).get("INVOICE_NO").toString());
									bill.get(i).setInvoice_date(operater1s0.get(0).get("INVOICE_DATE").toString());
								}
							}
						}
					} 
					// 当一级操作为合并时
					else if (operater1.get(j).get("REPRODUCE_TYPE").toString().equals("M")) {
						pamget.remove("param");
						pamget.put("param", "select DOCUMENT_NO, REPRODUCE_TYPE from TAX_R_DOC_REPRODUCE where COMPANY_ID = " + companyId + " and ORIGI_DOC_NO = '" + operater1.get(j).get("DOCUMENT_NO").toString() + "'");
						ArrayList<HashMap<String, Object>> operater1m = reportService.getCalculater(pamget);
						for (int k = 0; k < operater1m.size(); k++) {
							if (!Tools.isEmpty(operater1m.get(k).get("REPRODUCE_TYPE"))) {
								// 当二级操作为合并时
								if (operater1m.get(k).get("REPRODUCE_TYPE").toString().equals("M")) {
									pamget.remove("param");
									pamget.put("param", "select DOC_STATUS, isnull(INVOICE_CODE, '') as INVOICE_CODE, isnull(INVOICE_NO, '') as INVOICE_NO, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1m.get(k).get("DOCUMENT_NO").toString() + "'");
									ArrayList<HashMap<String, Object>> operater1m2m = reportService.getCalculater(pamget);
									String doc_status = operater1m2m.get(0).get("DOC_STATUS").toString();
									if (doc_status.equals("1") || doc_status.equals("9") || doc_status.equals("10") || doc_status.equals("11")) {
										bill.get(i).setAmount_opend(bill.get(i).getAmount_opend() + bill.get(i).getAmount_cur_total());
										bill.get(i).setAmount_unopend(bill.get(i).getAmount_cur_total() - bill.get(i).getAmount_opend());
										bill.get(i).setRate_opend(bill.get(i).getRate_opend() + bill.get(i).getTax_rate());
										bill.get(i).setInvoice_code(operater1m2m.get(0).get("INVOICE_CODE").toString());
										bill.get(i).setInvoice_no(bill.get(i).getInvoice_no() + "~" + operater1m2m.get(0).get("INVOICE_NO").toString());
										bill.get(i).setInvoice_date(operater1m2m.get(0).get("INVOICE_DATE").toString());
									}
								} 
								// 当二级为拆分时
								else {
									pamget.remove("param");
									pamget.put("param", "select DOC_STATUS, isnull(INVOICE_CODE, '') as INVOICE_CODE, isnull(INVOICE_NO, '') as INVOICE_NO, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1m.get(k).get("DOCUMENT_NO").toString() + "'");
									ArrayList<HashMap<String, Object>> operater1m2s = reportService.getCalculater(pamget);
									String doc_status = operater1m2s.get(0).get("DOC_STATUS").toString();
									if (doc_status.equals("1") || doc_status.equals("9") || doc_status.equals("10") || doc_status.equals("11")) {
										// 取得拆分前即一级合并后单据信息
										pamget.remove("param");
										pamget.put("param", "select DOC_STATUS, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1.get(j).get("DOCUMENT_NO").toString() + "'");
										ArrayList<HashMap<String, Object>> operater1mbefore2 = reportService.getCalculater(pamget);
										
										// 取得原始单据信息
										pamget.remove("param");
										pamget.put("param", "select DOC_STATUS, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + bill.get(i).getDocument_no() + "'");
										ArrayList<HashMap<String, Object>> origidoc = reportService.getCalculater(pamget);
										
										double amountopend = Double.valueOf(operater1m2s.get(0).get("AMOUNT_CUR_TOTAL").toString()) * Double.valueOf(origidoc.get(0).get("AMOUNT_CUR_TOTAL").toString()) / Double.valueOf(operater1mbefore2.get(0).get("AMOUNT_CUR_TOTAL").toString());
										double rateopend = Double.valueOf(operater1m2s.get(0).get("TAX_AMOUNT").toString()) * Double.valueOf(origidoc.get(0).get("TAX_AMOUNT").toString()) / Double.valueOf(operater1mbefore2.get(0).get("TAX_AMOUNT").toString());
										
										bill.get(i).setAmount_opend(bill.get(i).getAmount_opend() + amountopend);
										bill.get(i).setAmount_unopend(bill.get(i).getAmount_cur_total() - bill.get(i).getAmount_opend());
										bill.get(i).setRate_opend(bill.get(i).getRate_opend() + rateopend);
										bill.get(i).setInvoice_code(operater1m2s.get(0).get("INVOICE_CODE").toString());
										bill.get(i).setInvoice_no(bill.get(i).getInvoice_no() + "~" + operater1m2s.get(0).get("INVOICE_NO").toString());
										bill.get(i).setInvoice_date(operater1m2s.get(0).get("INVOICE_DATE").toString());
									}
								}
							} 
							// 一级为合并且无二级操作
							else {
								pamget.remove("param");
								pamget.put("param", "select DOC_STATUS, isnull(INVOICE_CODE, '') as INVOICE_CODE, isnull(INVOICE_NO, '') as INVOICE_NO, AMOUNT_CUR_TOTAL, TAX_AMOUNT, isnull(INVOICE_DATE, '') as INVOICE_DATE from TAX_D_ID_HEAD where COMPANY_ID = " + companyId + " and DOCUMENT_NO = '" + operater1m.get(k).get("DOCUMENT_NO").toString() + "'");
								ArrayList<HashMap<String, Object>> operater1m0 = reportService.getCalculater(pamget);
								String doc_status = operater1m0.get(0).get("DOC_STATUS").toString();
								if (doc_status.equals("1") || doc_status.equals("9") || doc_status.equals("10") || doc_status.equals("11")) {
									bill.get(i).setAmount_opend(bill.get(i).getAmount_opend() + Double.valueOf(operater1m0.get(0).get("AMOUNT_CUR_TOTAL").toString()));
									bill.get(i).setAmount_unopend(bill.get(i).getAmount_cur_total() - bill.get(i).getAmount_opend());
									bill.get(i).setRate_opend(bill.get(i).getRate_opend() + Double.valueOf(operater1m0.get(0).get("TAX_AMOUNT").toString()));
									bill.get(i).setInvoice_code(operater1m0.get(0).get("INVOICE_CODE").toString());
									bill.get(i).setInvoice_no(bill.get(i).getInvoice_no() + "~" + operater1m0.get(0).get("INVOICE_NO").toString());
									bill.get(i).setInvoice_date(operater1m0.get(0).get("INVOICE_DATE").toString());
								}
							}
						}
					}
				}
			}
			try {
				bill.get(i).setInvoice_no(bill.get(i).getInvoice_no().substring(1, bill.get(i).getInvoice_no().length()));
			} catch (Exception e) {
				logger.error("Exception: ", e.getMessage());
			}
			
			// 开票状态
			double amountTotal = bill.get(i).getAmount_cur_total();
			double amountOpend = bill.get(i).getAmount_opend();
			String invoiceStatus = null;
			if (lang.equals("en")) {
				if (amountTotal - amountOpend == 0) {
					invoiceStatus = "All invoicing";
				} else if (amountTotal - amountOpend == amountTotal) {
					invoiceStatus = "Unbilled";
				} else {
					invoiceStatus = "Part invoicing";
				}
			} else {
				if (amountTotal - amountOpend == 0) {
					invoiceStatus = "全部开票";
				} else if (amountTotal - amountOpend == amountTotal) {
					invoiceStatus = "未开票";
				} else {
					invoiceStatus = "部分开票";
				}
			}
			bill.get(i).setInvoice_status(invoiceStatus);
		}
		// 清空数据
		pamget.remove("param");
		pamget.put("param", "truncate table tax_rpt_customers_bill_data");
		reportService.getCalculater(pamget);
		// 保存数据
		for (int j = 0; j < bill.size(); j++) {
			reportService.saveBillData(bill.get(j));
		}
		// 将没有拆分合并的单据插入
		reportService.insertOrigiDoc(paramforbill);
		// 取出客户对账单临时表中所有客户
		pamget.remove("param");
		pamget.put("param", "select distinct CUST_NAME_CHN from tax_rpt_customers_bill_data");
		ArrayList<HashMap<String, Object>> allCust = reportService.getCalculater(pamget);
		// 更新合计
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		for (int i = 0; i < allCust.size(); i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("custname", allCust.get(i).get("CUST_NAME_CHN").toString());
			list.add(map);
		}
		HashMap<String, Object> paramForTotal = new HashMap<String, Object>();
		paramForTotal.put("cpn_id", companyId);
		paramForTotal.put("custname", list);
		reportService.updateTotal(paramForTotal);
	}
}
